package com.linkstec.util;

import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class DataSourceUtil {
	private static final Logger logger = LogManager.getLogger();

	private static Map<String, Properties> druidDSConfigMap;
	private static Map<String, DataSource> datasourceMap ;
	
	static {
		init();
	}

	/**
	 * 初始化配置信息
	 */
	@SuppressWarnings("rawtypes")
	public static void init(){
		try {
			druidDSConfigMap = new HashMap<String, Properties>();
			datasourceMap = new HashMap<String, DataSource>();
			
			Document document = null;
			InputStream input = Thread.currentThread().getContextClassLoader()
					.getResourceAsStream("datasource.xml");
			if(input!=null){
				SAXReader reader = new SAXReader();
				document = reader.read(input);
			}

			File f = new File(System.getProperty("user.dir") + "/" + "datasource.xml");
			if(f.exists()){
				SAXReader reader = new SAXReader();
				document = reader.read(f);
			}
			if(document == null){
				throw new RuntimeException("找不到数据库连接池配置文件datasource.xml");
			}
			Element root =  document.getRootElement();
			System.out.println(root.getName());
			// 枚举名称为foo的节点
			for ( Iterator i = root.elementIterator("dataSource"); i.hasNext();) {
				Element ds = (Element) i.next();
				String id = ds.attributeValue("id");
				Properties properties = new Properties();
				for(Iterator p = ds.elementIterator("property"); p.hasNext();){
					Element property = (Element) p.next();
					properties.setProperty(property.attributeValue("name"), property.attributeValue("value"));
				}
				if(id==null){
					id = "default";
				}
				druidDSConfigMap.put(id, properties);
			}
			logger.info("加载DataSource初始化参数：" + druidDSConfigMap.toString());;
		} catch (DocumentException e) {
			throw new RuntimeException("加载数据库连接池配置出错 错误信息:" + e.getMessage());
		}
	}

	/**
	 * 默认的数据库连接获取
	 * @return
	 */
	public static final DataSource getDataSource(){
		return getDataSource("default");
	}

	/**
	 *  数据库连接获取
	 * @param id 数据库连接池ID
	 * @return
	 */
	public static final DataSource getDataSource(String id) {
		if(datasourceMap.get(id) != null){
			return datasourceMap.get(id);
		}
		
		Properties properties = druidDSConfigMap.get(id);
		if(properties==null){
			throw new RuntimeException("没有找到的Datasource配置信息(ID=" + id + ")");
		}
		
		DataSource ds = null;
		try {
			ds = DruidDataSourceFactory.createDataSource(properties);
			datasourceMap.put(id, ds);
		} catch (Exception e) {
			throw new RuntimeException("创建数据库连接池出错(ID=" + id + ") 错误信息:" + e.getMessage());
		}
		
		return ds;
	}
	
	/**
	 * 从默认数据库连接池获取连接
	 * @return
	 */
	public static final Connection getConnection(){
		return getConnection("java:/datasources/HTMotBatchDS");
	}
	
	/**
	 * 从数据库连接池获取连接
	 * @param id 数据库连接池ID
	 * @return
	 */
	public static final Connection getConnection(String id){
		DataSource ds =  getDataSource(id);

		Connection conn = null;
		try {
			conn = ds.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException("从数据库连接池获取连接出错，错误信息:" + e.getMessage());
		}
		return conn;
	}
	public static void main(String[] args) {
		Connection  conn = getConnection();
        String querySql = "SELECT COUNT(1) AS CNT FROM MOT_BASE.TABLE_STATUS T WHERE T.TABLE_NAME = '" + "my_test" +"' AND T.DATA_STATUS = '1'";
        
		try {
			Map<String, Object> existFg = DbUtil.queryOne(conn, querySql, null);
			Long cnt = 0L;
			if (existFg.get("cnt") != null) {
				cnt = ConvertUtil.convert(existFg.get("cnt"),Long.class);
				if (cnt <= 0) {
					System.out.println("adfasdf");
				}
				System.out.println(cnt);
			} else {
				System.out.println("ddddd");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}